<?php

namespace app\common\model;

use Carbon\Carbon;
use think\Model;


class Card extends Model
{

    

    

    // 表名
    protected $name = 'card';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];


    public function getCardDisplayList()
    {
        return ['0' => __('Card_display 0'), '1' => __('Card_display 1')];
    }

    public function store()
    {
        return $this->belongsTo('\\app\\admin\\model\\Store', 'store_id', 'id')->setEagerlyType(1);;
    }

    public function room()
    {
        return $this->belongsTo('\\app\\admin\\model\\Room', 'room_id', 'id')->setEagerlyType(1);;
    }

    static public function getCouldUseCardList($userId, $reserveDate, $reserveDuration, $roomId)
    {
        $room = Room::get($roomId);
        $storeId = $room->store_id;

        $cards = \app\admin\model\user\Card::where('user_id', $userId)
            ->where("FIND_IN_SET($roomId, store_ids)")
            ->select();
        $cards = array_filter($cards, function ($e) use ($reserveDate, $reserveDuration) {
            $reserveDateC = Carbon::parse($reserveDate)->endOfDay(); //让用户当天就能用上买的券
            $serviceStart = Carbon::parse($e->service_start);
            $serviceEnd = Carbon::parse($e->service_end);

            // 按次卡的过滤方式
//            if ($reserveDateC->betweenIncluded($serviceStart, $serviceEnd)
//                and $e->max_hour * 60 >= $reserveDuration
//                and $e->checknum > $e->hascheckednum) {
//                return true;
//            }

            // 按小时卡的过滤方式
            /*
            if ($reserveDateC->betweenIncluded($serviceStart, $serviceEnd)
                and $e->total_hour * 60 >= $e->hasconsumedhour * 60 + $reserveDuration) {
                return true;
            }
             */
            // 组合支付后，这里不需要加时间判断
            if ($e->total_hour > $e->hasconsumedhour) {
                return true;
            }
        });
        $rooms = \app\admin\model\Room::all();
        // 所有门店的教室ID集合
        $store2RoomIds = [];
        // 所有教室对应的门店ID
        $room2StoreIds = [];
        foreach ($rooms as $r) {
            $room2StoreIds[$r->id] = $r->store_id;
            if (!isset($store2RoomIds[$r->store_id])) {
                $store2RoomIds[$r->store_id] = [];
            }
            $store2RoomIds[$r->store_id][] = $r->id;
        }
        // 所有门店ID
        $stores = \app\common\model\Store::all();
        $storeIds = array_map(function ($e) {
            return $e['id'];
        }, $stores);
        
        $rooms = \app\admin\model\Room::with('store')->select();
        $roomIds = array_map(function ($e) {
            return $e['id'];
        }, $rooms);

        $roomNameMap = [];
        foreach ($rooms as $v) {
            $roomNameMap[$v['id']] = $v['store']['store_name'] . ' - ' . $v['room_name'];
        }

        // 当key不是0开始时，在小程序的js端，会被当成对象处理
        $couldUserCards = [];
        foreach ($cards as $v) {
            // 设置的教室
            $setRoomIds = explode(',', $v->store_ids);
            // 设置的门店
            $setStoreIds = [];
            // 相关门店的教室总数
            $totalRoom = 0;
            foreach ($setRoomIds as $rId) {
                if (isset($room2StoreIds[$rId]) && !in_array($room2StoreIds[$rId], $setStoreIds)) {
                    $setStoreIds[] = $room2StoreIds[$rId];
                    $totalRoom += count($store2RoomIds[$room2StoreIds[$rId]]);
                }
            }
            $countRoom = count($setRoomIds);
            $countStore = count($setStoreIds);
            
            $v->room_name = '点击查看';
            /*
            if ($totalRoom == $countRoom) {
                $v->room_name = '在适用门店内全教室通用';
            } else {
                $v->room_name = "适用${countRoom}个教室";
            }
             */
            if ($countStore == count($storeIds)) {
                $v->store_name = '适用全部门店';
            } else {
                $v->store_name = "适用${countStore}家门店";
            }
            $v->room_name_list = '';
            $roomsList = [];
            $ids = explode(',', $v->store_ids);
            foreach ($ids as $vv) {
                $v->room_name_list .= $roomNameMap[$vv] . "\n";
                $roomsList[] = $roomNameMap[$vv];
            }
            $v->rooms_list = $roomsList;

            $couldUserCards[] = $v;
        }

        return $couldUserCards;

    }


}
